import '../../domain/entities/favorite.dart';
import '../../domain/entities/anime.dart';
import '../../domain/repositories/favorite_repository.dart';
import '../datasources/favorite_local_datasource.dart';
import '../datasources/anime_local_datasource.dart';
import '../models/favorite_model.dart';
import '../models/anime_model.dart';

/// 收藏数据仓库实现
class FavoriteRepositoryImpl implements FavoriteRepository {
  final FavoriteLocalDataSource _localDataSource;
  final AnimeLocalDataSource _animeLocalDataSource;

  FavoriteRepositoryImpl({
    required FavoriteLocalDataSource localDataSource,
    required AnimeLocalDataSource animeLocalDataSource,
  }) : _localDataSource = localDataSource,
       _animeLocalDataSource = animeLocalDataSource;

  @override
  Future<List<Anime>> getFavorites() async {
    // 优先从动漫缓存获取收藏列表
    final cachedAnimeList = await _animeLocalDataSource.getCachedFavoriteAnimeList();
    if (cachedAnimeList.isNotEmpty) {
      return cachedAnimeList.map((model) => model.toEntity()).toList();
    }

    // 从收藏数据源获取
    final favorites = await _localDataSource.getAllFavorites();
    final animeList = favorites.map((fav) => fav.toEntity().anime).toList();
    
    // 缓存到动漫缓存中
    if (animeList.isNotEmpty) {
      final animeModels = animeList.map((anime) => AnimeModel.fromEntity(anime)).toList();
      await _animeLocalDataSource.cacheFavoriteAnimeList(animeModels);
    }
    
    return animeList;
  }

  @override
  Future<void> addFavorite(Anime anime, [FavoriteStatus? status]) async {
    final finalStatus = status ?? FavoriteStatus.wantToWatch;
    print('Repository添加收藏：动漫《${anime.title}》, 状态=${finalStatus.displayName}');
    
    final favorite = Favorite(
      id: '${anime.id}_${DateTime.now().millisecondsSinceEpoch}',
      animeId: anime.id,
      anime: anime,
      status: finalStatus, // 使用传入的状态或默认状态
      addedDate: DateTime.now(),
    );

    final model = FavoriteModel.fromEntity(favorite);
    await _localDataSource.addFavorite(model);
    
    // 同时添加到动漫缓存
    await _animeLocalDataSource.addFavoriteToCache(AnimeModel.fromEntity(anime));
    
    print('收藏添加成功');
  }

  @override
  Future<void> removeFavorite(int animeId) async {
    await _localDataSource.removeFavorite(animeId);
    
    // 同时从动漫缓存中移除
    await _animeLocalDataSource.removeFavoriteFromCache(animeId);
  }

  @override
  Future<void> updateFavoriteStatus(int animeId, FavoriteStatus status) async {
    final existing = await _localDataSource.getFavorite(animeId);
    if (existing != null) {
      final updated = existing.updateStatus(status);
      await _localDataSource.updateFavorite(updated);
    }
  }

  @override
  Future<void> updateWatchedEpisodes(int animeId, int watchedEpisodes) async {
    final existing = await _localDataSource.getFavorite(animeId);
    if (existing != null) {
      final updated = existing.updateWatchedEpisodes(watchedEpisodes);
      await _localDataSource.updateFavorite(updated);
    }
  }

  @override
  Future<void> updatePersonalScore(int animeId, double score) async {
    final existing = await _localDataSource.getFavorite(animeId);
    if (existing != null) {
      final updated = existing.updatePersonalScore(score);
      await _localDataSource.updateFavorite(updated);
    }
  }

  @override
  Future<void> updateNotes(int animeId, String notes) async {
    final existing = await _localDataSource.getFavorite(animeId);
    if (existing != null) {
      final updated = existing.updateNotes(notes);
      await _localDataSource.updateFavorite(updated);
    }
  }

  @override
  Future<List<Favorite>> getAllFavorites() async {
    final models = await _localDataSource.getAllFavorites();
    return models.map((model) => model.toEntity()).toList();
  }

  @override
  Future<List<Favorite>> getFavoritesByStatus(FavoriteStatus status) async {
    final models = await _localDataSource.getFavoritesByStatus(status);
    return models.map((model) => model.toEntity()).toList();
  }

  @override
  Future<bool> isFavorite(int animeId) async {
    // 优先检查动漫缓存
    final isInCache = await _animeLocalDataSource.isFavoriteInCache(animeId);
    if (isInCache) return true;
    
    // 再检查收藏数据源
    return await _localDataSource.isFavorite(animeId);
  }

  @override
  Future<Favorite?> getFavorite(int animeId) async {
    final model = await _localDataSource.getFavorite(animeId);
    return model?.toEntity();
  }

  @override
  Future<void> clearFavorites() async {
    await _localDataSource.clearAllFavorites();
    
    // 清空动漫缓存中的收藏列表
    await _animeLocalDataSource.cacheFavoriteAnimeList([]);
  }

  @override
  Future<Map<FavoriteStatus, int>> getFavoriteStats() async {
    final stats = await _localDataSource.getFavoriteStats();
    final result = <FavoriteStatus, int>{};
    
    for (final status in FavoriteStatus.values) {
      result[status] = stats[status.key] ?? 0;
    }
    
    return result;
  }

  /// 搜索收藏
  Future<List<Favorite>> searchFavorites(String query) async {
    final models = await _localDataSource.searchFavorites(query);
    return models.map((model) => model.toEntity()).toList();
  }

  /// 按日期排序获取收藏
  Future<List<Favorite>> getFavoritesSortedByDate({bool ascending = false}) async {
    final models = await _localDataSource.getFavoritesSortedByDate(ascending: ascending);
    return models.map((model) => model.toEntity()).toList();
  }

  /// 按评分排序获取收藏
  Future<List<Favorite>> getFavoritesSortedByScore({bool ascending = false}) async {
    final models = await _localDataSource.getFavoritesSortedByScore(ascending: ascending);
    return models.map((model) => model.toEntity()).toList();
  }

  /// 获取最近添加的收藏
  Future<List<Favorite>> getRecentFavorites({int limit = 10}) async {
    final models = await _localDataSource.getRecentFavorites(limit: limit);
    return models.map((model) => model.toEntity()).toList();
  }

  @override
  Future<int> getFavoriteCount() async {
    return await _localDataSource.getFavoriteCount();
  }

  @override
  Future<void> clearAllFavorites() async {
    await _localDataSource.clearAllFavorites();
    
    // 清空动漫缓存中的收藏列表
    await _animeLocalDataSource.cacheFavoriteAnimeList([]);
  }
} 